using System.IO;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;


namespace XmlFieldType
{
    public class XmlField : BaseXmlField
    {
        private SPFieldXml field;
      
        public XmlField(SPFieldXml parentField)
        {
            this.field = parentField;
        }
    
        protected override void Render(HtmlTextWriter output)
        {
            
            if (string.IsNullOrEmpty(this.field.RenderXml))
            {
                base.Render(output);
            }
            else
            {
                //Don't use standard rendering templates
                if (IsTranformTemplateDefined(ControlMode.ToString()))
                {
                    //Use the attached xslt to render our xml
                    RenderUsingXslt(output);
                }
                else
                {
                    base.Render(output);
                }

            }
        }
        
        private void RenderUsingXslt(HtmlTextWriter output)
        {

            XslCompiledTransform transform = new XslCompiledTransform();
            StringReader sr = new StringReader(this.field.RenderXml);
            XmlReader rdr = XmlReader.Create(sr);
            transform.Load(rdr);

            XPathNavigator inputNav = this.field.GetFieldXml(this.ItemFieldValue.ToString()).CreateNavigator();
            XsltArgumentList args = new XsltArgumentList();
            args.AddParam("ControlMode", string.Empty, this.ControlMode.ToString());
            transform.Transform(inputNav, args, output);

        }

        private bool IsTranformTemplateDefined(string controlMode)
        {
            //Load up the transform, make sure we have a template for the control mode

            XmlDocument transform = new XmlDocument();

            transform.LoadXml(this.field.RenderXml);

            XmlNamespaceManager mgr = new XmlNamespaceManager(transform.NameTable);

            mgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");

            string query = string.Format("//xsl:template[@name='{0}']", controlMode);

            if (transform.SelectSingleNode(query, mgr) == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}


